<?php
/**
 * User: xuanbang.wen
 * Date: 2019/9/25
 */

namespace App\Web\Controller;


use App\Web\Facades\UserAuth;
use App\Web\Model\CaseModel;
use App\Web\Model\CaseOperator;
use App\Web\Model\EhireUser as UserModel;
use EchoPHP\Facades\Db;
use EchoPHP\Http\Request;
use App\Web\Model\CustomerAccount as AccountModel;
use App\Web\Model\Customer as CustomerModel;
use EchoPHP\Validator\Validator;

class CustomerAccount extends Controller {
    public function show(Request $request) {
        $subId = $request->getParam('subid', 0);
        //在客户详情页展示使用
        $result1 = (new CustomerModel())->myCostumer(['subid' => $subId]);
        $myCustomerSubIds = array_column($result1, 'subid');
        //在职位详情页联想职位联系人使用
        $result2 = (new CaseOperator())->myAllCase(UserAuth::getLoginId());
        $myCaseSubIds = array_column($result2, 'subid');
        if (!in_array($subId, array_merge($myCustomerSubIds, $myCaseSubIds))) {
            return $this->json(['status' => false, 'message' => '您无权查看该信息', 'accountlist' => []]);
        }
        return $this->json(
            [
                'status' => true,
                'message' => '获取成功',
                'accountlist' => (new AccountModel())->show($subId)
            ]
        );
    }

    /**
     * 获取带是否为职位联系人的客户联系人列表（职位添加联系人时用）
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getSubContactorList(Request $request) {
        $subId = $request->getParam('subid', 0);
        $caseId = $request->getParam('caseid',0);

        return $this->json(
            ['status' => true,
                'message' => '获取成功',
                'accountlist' => (new AccountModel())->getSubContactorList($subId,$caseId)
            ]
        );
    }

    /**
     * 客户详情页添加客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function addContactorInCustomer(Request $request) {
        $params = [
            'email' => $request->getParam('email'),
            'subid' => $request->getParam('subid'),
            'cname' => $request->getParam('cname'),
            'memo' => $request->getParam('memo'),
            'department' => $request->getParam('department'),
            'mobilephone' => $request->getParam('mobilephone'),
            'isinterviewer' => $request->getParam('isinterviewer',0)
        ];
        $accountModel = new AccountModel();
        $checkResult = $accountModel->addContactorDataCheck($params);
        if ($checkResult['status'] == false) {
            return $this->json($checkResult);
        }
        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }
        $customerModel = new CustomerModel();
        //检查客户负责人权限
        if (!$customerModel->chkEditSubRight($params['subid'])) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $result = $accountModel->add($params);
        return $this->json($result);
    }

    /**
     * 客户管理页编辑客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function edit(Request $request) {
        $params = [
            'accountid' => $request->getParam('accountid'),
            'email' => $request->getParam('email'),
            'cname' => $request->getParam('cname'),
            'subid' => $request->getParam('subid'),
            'memo' => $request->getParam('memo'),
            'department' => $request->getParam('department'),
            'mobilephone' => $request->getParam('mobilephone'),
            'isinterviewer' => $request->getParam('isinterviewer',0)
        ];
        $rule = [
            'accountid|客户账户id' => [
                'required', 'number'
            ],
            'email|客户账户邮箱' => [
                'required', 'email'
            ],
            'subid|客户id' => [
                'required', 'number'
            ],
            'cname|客户账户名称' => [
                'required', 'maxLength' => 50
            ],
            'mobilephone|面试官手机' => [
                'required', 'minLength' => 7, 'maxLength' => 19
            ],
            'department|部门' => [
                'maxLength' => 50
            ],
            'memo|备注' => [
                'maxLength' => 200
            ],
        ];
        $validate = new Validator($rule);
        if (!$validate->validate($params)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => $validate->getErrors()
            ]);
        }
        if ((preg_match('/(^(((\+)?\d{1,4}-)\d{5,15}$)|(^1\d{10}$))/', $params['mobilephone']) == 0) && (preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?(\(0\d{2,3}\)|0\d{2,3})?(\(0\d{2,3}\)|0\d{2,3})?[1-9]\d{6,7}(\-\d{1,5})?$/', $params['mobilephone']) == 0)) {
            return $this->json([
                'status' => false,
                'message' => '字段校验失败',
                'validateFailure' => ['mobilephone' => '手机/座机格式不正确']
            ]);
        }
        $params['mobilephone'] = ltrim($params['mobilephone'], '+');
        $phoneArr = explode("-", $params['mobilephone']);
        if (count($phoneArr) == 2) {
            if ($phoneArr[0] == 86) {
                $params['mobilephone'] = $phoneArr[1];
            } else {
                // $params['mobilephone'] = ltrim($params['mobilephone'], 0);
            }
        }
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubRight($params['subid'])) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        return $this->json((new AccountModel())->edit($params));
    }

    //绑定网才
    public function bindEhire(Request $request) {
        $accountId = $request->getParam('accountid');
        $ehireInfo = [
            'ehirectmid' => $request->getParam('ehirectmid', 0),
            'ehireaccid' => $request->getParam('ehireaccid', 0),
        ];
        $subId = $request->getParam('subid');
        if (!(new CustomerModel)->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $result = (new AccountModel())->bindEhire($accountId, $ehireInfo);
        return $this->json($result);
    }

    /**
     * 客户管理页删除客户联系人
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function lock(Request $request) {
        $accountId = $request->getParam('accountid');
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $result = (new AccountModel())->lock($accountId, $subId);
        return $this->json(
            [
                'status' => $result == 1,
                'message' => $result == 1 ? '修改成功' : '修改失败',
            ]
        );
    }

    /**
     * 客户详情页删除客户联系人时判断是否已被职位绑定
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function deleteCheck(Request $request) {
        $accountId = $request->getParam('accountid');
        $subId = $request->getParam('subid');
        $customerModel = new CustomerModel();
        if (!$customerModel->chkEditSubRight($subId)) {
            return $this->json(['status' => 0, 'message' => '您无权编辑该客户']);
        }
        $sql = 'select 1 from CaseContacter where accountid = ? and subid = ? and status = ?';
        $var = [$accountId,$subId,'01'];
        $result = Db::selectOne($sql,$var);
        if (!empty($result)) {
            return $this->json([
                'status' => 1,
                'message' => '该联系人已被交易公司下的职位绑定，确定删除吗？'
            ]);
        }
        return $this->json([
            'status' => 2,
            'message' => '校验成功'
        ]);
    }

    /**
     * 客户联系人绑定用户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function bindUser(Request $request) {
        $accountId = $request->getPost('accountid');
        $hrUid = $request->getPost('hruid');
        $ctmId = $request->getPost('ctmid');
        $subId = $request->getPost('subid');
        $userId = $this->getLoginId();

        if (!(new CustomerModel)->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $userModel = new UserModel();
        $resultBody = $userModel->bindUser($subId, $userId, $accountId, $ctmId, $hrUid);

        return $this->json(
            $resultBody
        );
    }

    /**
     * 客户联系人取消绑定
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function unbindUser(Request $request) {
        $subId = $request->getPost('subid');
        $accountId = $request->getPost('accountid');
        if (empty($accountId) || empty($subId)) {
            return $this->json(['status' => false, 'message' => '参数非法']);
        }
        $userId = $this->getLoginId();
        if (!(new CustomerModel)->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $userModel = new UserModel();
        $resultBody = $userModel->unbindUser($userId, $subId, $accountId);

        return $this->json(
            $resultBody
        );
    }

    /**
     * 获取用户列表 无需登录的情况
     * @param \EchoPHP\Http\Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getEhireUserList() {
        $ctmId = $this->request->getPost('ctmid', 0);
        $pageIndex = $this->request->getPost('pagenum');
        $pageSize = $this->request->getPost('pagelimit');
        $sort = $this->request->getPost('sort');
        $subId = $this->request->getPost('subid');
        $where = [
            'username' => $this->request->getPost('username'),
            'email' => $this->request->getPost('email'),
            'name' => $this->request->getPost('mobile'),
            'hruids' => $this->request->getPost('hruids'),
            'activestatus' => $this->request->getPost('activestatus')
        ];

        $whereString = '';
        foreach ($where as $key => $item) {
            if ($item != null) {
                $whereString .= $key . '|' . urlencode($item) . '&';
            }
        }
        $whereString = trim($whereString, '&');
        if (!(new CustomerModel)->chkEditSubRight($subId)) {
            return $this->json(['status' => false, 'message' => '您无权编辑该客户']);
        }
        $userModel = new UserModel();
        $resultBody = $userModel->getUserListWithNoToken($ctmId, $pageIndex, $pageSize, $sort, $whereString);

        return $this->json(
            $resultBody
        );
    }

    /**
     * Notes:获取subid对应crmsubid下ctm列表以及其下用户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getCtmList(Request $request){
        $subId = $request->getParam('subid');
        $model = new AccountModel();
        $res = $model->getCtmList($subId);
        return $this->json([
            'status' => true,
            'message' => '获取成功',
            'ctmlist' => $res
        ]);
    }
}